import logging
from advanced_json_encoding import decode

from datetime import datetime

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pylons.decorators.rest import restrict

from sc_console.lib.base import BaseController, render
from sc_console.model.models import ErrorReport, YouTubePartialParse
from sc_console.model.models import Heartbeat, HeartbeatResponse
from sc_console.model.meta import Session

log = logging.getLogger(__name__)

class UploadController(BaseController):
    def __before__(self):
        self.data = decode(request.body, key_names_to_strings=True)

    @restrict('POST')
    def heartbeat(self):
        heartbeat_data = Heartbeat(self.data['time'])
        Session.add(heartbeat_data)
        Session.commit()

    @restrict('POST')
    def heartbeat_response(self):
        app_name = self.data['app_name']
        heartbeat = self.data['time_responding_to']

        heartbeat_data = Session.query(Heartbeat).get(heartbeat)

        if heartbeat_data is None:
            heartbeat_data = Heartbeat(heartbeat)
            Session.add(heartbeat_data)

        heartbeat_data.add_response(app_name, self.data['response_time'])

        Session.commit()

    @restrict('POST')
    def error(self):
        data = decode(request.body, key_names_to_strings=True)

        error = ErrorReport(time=datetime.now(), **data)

        Session.add(error)
        Session.commit()

    @restrict('POST')
    def youtube_partial_parse(self):
        data = decode(request.body, key_names_to_strings=True)

        video_id = data['video_id']

        pp = Session.query(YouTubePartialParse)\
                .filter(YouTubePartialParse.video_id == video_id).first()

        if pp:
            for key, value in data.items():
                setattr(pp, key, value)
        else:
            pp = YouTubePartialParse(time=datetime.now(), **data)
            Session.add(pp)

        Session.commit()

